import './style.css'
let timer:number|null;
window.onload = function() {
  let show = true
  let count = 200000
  let time = 0
  let color = 'red'
  let renderType = 'dom' // dom 添加dom  拼接字符串 str


  // 获取到 DOM 元素
  const showText = document.querySelector('.show')
  const lenText = document.querySelector('.len')
  const timeText = document.querySelector('.time')

  // 容器
  const mainDom = document.getElementById('main')

  // 获取到按钮
  const redBtn = document.getElementById('redBtn')
  const greenBtn = document.getElementById('greenBtn')
  const toggleBtn = document.getElementById('toggleBtn')

  // 切换背景色
  const onBg = (c:string) => {
    const child = mainDom && mainDom.children ? mainDom.children : [];
    for (let i = 0; i < child.length; i++) {
      const item = child[i] as HTMLElement;
      item  && (item.style.backgroundColor = c);
    }

    const t = Date.now()
    const lastDom = document.getElementById('box_' + (count - 1))
    timer = setInterval(() => {
      if (lastDom?.style.backgroundColor === c) {
        clearInterval(timer as number)
        timer = null
        time = Date.now() - t
        setVal()
      }
    });
  }

  redBtn && (redBtn.onclick = () => onBg('red'))
  greenBtn && (greenBtn.onclick = () => onBg('green'))

  // 切换/显示
  const onToggle = () => {
    show = !show
    if (!show) {
      return mainDom && (mainDom.innerHTML = '');  
    }

    render()
  }

  toggleBtn && (toggleBtn.onclick = onToggle)

  // 渲染
  const render = () => {
    const radioDom = document.querySelector("input[name='render']:checked") as HTMLInputElement;
    const renderType = radioDom.value; // 渲染方式 dom  str
    if (renderType === 'dom') {
      const span = document.createElement('span')
      span.className = 'box'
      span.style.backgroundColor = color;
      for (let i = 0; i < count; i++) {
        const itemSpan = span.cloneNode(true) as HTMLElement;
        itemSpan.id = 'box_' + i;
        mainDom && mainDom.appendChild(itemSpan)
      }
    } else {
      var html = ''
      for (let i = 0; i < count; i++) {
        html += `<span class="box" style="background-color: ${color}" id="box_${i}"></span>`
      }
      mainDom && (mainDom.innerHTML = html)
    }

    const t = Date.now()
    timer = setInterval(() => {
      if (document.getElementById('box_' + (count - 1))) {
        clearInterval(timer as number)
        timer = null
        time = Date.now() - t
        setVal()
      }
    });
  }
  render();

  // 设置值
  const setVal = () => {
    lenText && (lenText.innerHTML = count + '')
    timeText && (timeText.innerHTML = time + '')
    showText && (showText.innerHTML = show ? '显示' : '隐藏')
  }
}

